package org.budo.beetl.resource.multiple;

import java.util.List;

import org.beetl.core.GroupTemplate;
import org.beetl.core.Resource;
import org.beetl.core.ResourceLoader;
import org.beetl.core.misc.BeetlUtil;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author limingwei
 */
@Slf4j
@Getter
@Setter
public class BudoMultipleBeetlResourceLoader implements ResourceLoader {
    private List<ResourceLoader> resourceLoaders;

    @Override
    public void init(GroupTemplate groupTemplate) {
        log.info("#60 init, this=" + this + ", groupTemplate=" + groupTemplate);

        for (ResourceLoader resourceLoader : this.getResourceLoaders()) {
            resourceLoader.init(groupTemplate);
        }
    }

    @Override
    public boolean exist(String key) {
        List<ResourceLoader> resourceLoaders = this.getResourceLoaders();
        for (ResourceLoader resourceLoader : resourceLoaders) {
            boolean exist = resourceLoader.exist(key);
            log.debug("#37 resourceLoader={}, key={}, exist={}", resourceLoader, key, exist);

            if (exist) {
                return true;
            }
        }

        return false;
    }

    @Override
    public Resource getResource(String key) {
        for (ResourceLoader resourceLoader : this.getResourceLoaders()) {
            boolean exist = resourceLoader.exist(key);
            if (exist) {
                return resourceLoader.getResource(key);
            }
        }

        throw new RuntimeException("#50 key=" + key + ", resourceLoaders=" + this.getResourceLoaders());
    }

    @Override
    public String getResourceId(Resource resource, String id) {
        if (null == resource) {
            return id;
        }

        String relPath = BeetlUtil.getRelPath(resource.getId(), id);
        return relPath;
    }

    @Override
    public boolean isModified(Resource key) {
        for (ResourceLoader resourceLoader : this.getResourceLoaders()) {
            if (resourceLoader.isModified(key)) {
                return true;
            }
        }

        return false;
    }

    @Override
    public void close() {
        throw new RuntimeException();
    }

    @Override
    public String getInfo() {
        throw new RuntimeException();
    }
}